<?php

/**
 * @Author: king
 * @Date:   2019-05-04 19:16:44
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-26 11:47:39
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use AstroTool\Cache\CacheManage;
use Illuminate\Database\Eloquent\Model;
use Cache;

class LanmeiTag extends Model
{
    protected $table = 'astro_tag';

    /**
     * 获取标签信息
     * @param int $type
     * @return array
     * @throws \Exception
     */
    public static function getTag($type = 0)
    {
        $data = CacheManage::getInstance()->setCacheConfig('zhunle_tag', $type)
            ->getDataAndSet(function () use ($type)
            {
                return json_encode(self::getTagsByData($type));
            });

        return json_decode($data, true);
    }

    /**
     * 获取标签数据
     * @param int $type
     * @return array
     * @throws ApiException
     */
    protected static function getTagsByData(int $type)
    {
        try
        {
            $data = self::where(['tag_type' => $type, 'status' => 1])->orderBy('sort', 'DESC')->select('id','tag_name')->get();
            $data = collect($data)->toArray();
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * 获取tag_id为数组键的tag数据 [1=>'婚恋' 2=>'财富']
     * @param $type
     * @return array
     * @throws \Exception
     */
    public static function getTagData($type)
    {
        $tags = self::getTag($type);
        $data = [];
        foreach ($tags as $tagItem)
        {
            $data[$tagItem['id']] = $tagItem['tag_name'];
        }

        return $data;
    }

    /**
     * 通过ID 和 标签类型获取标签名称
     * @param $type 1占星/占卜 2评论 3举报
     * @param $tid
     * @return string
     * @throws \Exception
     */
    public static function getTagNameById($type, $tid)
    {
        $tagData = self::getTagData($type);

        $tagName = $tagData[$tid] ?? '';

        return $tagName;
    }
}
